<template>
  <view class="page">
    <!-- 标题 -->
    <view class="header">
      <text class="title">我的待收货订单</text>
    </view>

    <!-- 搜索框 -->
    <view class="search-box">
      <input 
        class="search-input" 
        placeholder="请输入订单编号搜索"
        v-model="searchText"
      />
	  <button
	    class="search-btn" 
	    @tap="handleSearch"
	    :disabled="loading"
	  >
	  </button>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <text>加载中...</text>
    </view>

    <!-- 空状态 -->
    <view v-else-if="orders.length === 0" class="empty-container">
      <text>暂无订单记录</text>
    </view>

    <!-- 订单列表 -->
    <view v-else class="order-list">
      <view class="order-detail" v-for="(order, index) in filteredOrders" :key="index">
        <view class="order-item-row">
          <text class="order-label">订单编号</text>
          <text class="order-value">{{ order.orderNumber || '-' }}</text>
        </view>
        <view class="order-item-row">
          <text class="order-label">课程名称</text>
          <text class="order-value">{{ order.courses.courseName || '-' }}</text>
        </view>
        <view class="order-item-row">
          <text class="order-label">姓名</text>
          <text class="order-value">{{ order.users.username || '-' }}</text>
        </view>
        <view class="order-item-row">
          <text class="order-label">金额</text>
          <text class="order-value">¥{{ order.paymentAmount || '0' }}</text>
        </view>
        <view class="order-item-row">
          <text class="order-label">创建时间</text>
          <text class="order-value">{{ order.orderDate || '0' }}</text>
        </view>
        
        <!-- 操作按钮区域 -->
        <view class="action-buttons">
          <button 
            class="refund-btn" 
            @tap="refundOrder(order.orderId)"
            :disabled="isProcessing[order.orderId]"
          >
            <text v-if="isProcessing[order.orderId]">处理中...</text>
            <text v-else>申请退款</text>
          </button>
          <button 
            class="confirm-btn" 
            @tap="confirmReceipt(order.orderId)"
            :disabled="isProcessing[order.orderId]"
          >
            <text v-if="isProcessing[order.orderId]">处理中...</text>
            <text v-else>确认收货</text>
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore  } from'@/stores/api.js'

const userStore = useUserStore ();
// 搜索文本
const searchText = ref('')

// 加载状态
const loading = ref(true)

// 订单数据
const orders = reactive([])
//提交修改订单状态的对象
let userOrder = reactive({
  orderId:null,
  paymentStatus:''
})

// 按钮处理状态
const isProcessing = reactive<Record<string, boolean>>({})

// 过滤订单数据
const filteredOrders = computed(() => {
  return orders.filter(order => 
    order.orderNumber.includes(searchText.value) ||
    order.courses?.courseName.includes(searchText.value) ||
    order.users?.username.includes(searchText.value)
  )
})

// 页面加载完成后执行
onMounted(() => {
  console.log('订单页面已加载')
  fetchOrders()
})

let userOrders = reactive({
  userId: userStore.getUserId,
  paymentStatus: "待收货",
  orderNumber: ""
})
// 处理搜索
const handleSearch = () => {
  userOrders.orderNumber = searchText.value
  fetchOrders()
}
// 获取订单数据
const fetchOrders = () => {
  loading.value = true
  
  uni.request({
    url: 'http://127.0.0.1:8088/order/findAll',
    method: 'GET',
    data: userOrders,
    success: (res) => {
      console.log('订单数据获取成功:', res.data)
      
      // 假设接口返回格式为 { code: 200, data: [...订单数据] }
      if (res.data.code == 200) {
        // 清空原有数据并添加新数据
        orders.splice(0, orders.length, ...res.data.data)
        console.log("我拿到了")
        console.log(orders)
      } else {
        uni.showToast({
          title: '获取订单失败',
          icon: 'none'
        })
      }
    },
    fail: (err) => {
      console.error('订单数据获取失败:', err)
      uni.showToast({
        title: '网络请求失败',
        icon: 'none'
      })
    },
    complete: () => {
      loading.value = false
    }
  })
}

// 申请退款
const refundOrder = (orderId: string) => {
  // 设置按钮为处理中状态
  isProcessing[orderId] = true
  
  uni.showModal({
    title: '申请退款',
    content: '确定要申请退款吗？退款申请提交后将由商家审核',
    success: (res) => {
      if (res.confirm) {
		userOrder.paymentStatus = '售后中'
		userOrder.orderId = orderId
        uni.request({
          url: `http://127.0.0.1:8088/order/updateById`,
		  data: userOrder,
          method: 'POST',
          success: (res) => {
            if (res.data.code === 200) {
              uni.showToast({
                title: '退款申请已提交',
                icon: 'success'
              })
              // 刷新订单列表
              fetchOrders()
            } else {
              uni.showToast({
                title: '申请失败: ' + res.data.message,
                icon: 'none'
              })
            }
          },
          fail: (err) => {
            console.error('退款申请失败:', err)
            uni.showToast({
              title: '网络请求失败',
              icon: 'none'
            })
          },
          complete: () => {
            // 重置按钮状态
            isProcessing[orderId] = false
          }
        })
      } else {
        // 用户取消操作，重置按钮状态
        isProcessing[orderId] = false
      }
    }
  })
}

// 确认收货
const confirmReceipt = (orderId: string) => {
  // 设置按钮为处理中状态
  isProcessing[orderId] = true
  
  uni.showModal({
    title: '确认收货',
    content: '确认收货后，系统将自动完成订单并结算款项给商家',
    success: (res) => {
		userOrder.paymentStatus = '已完成'
		userOrder.orderId = orderId
      if (res.confirm) {
        uni.request({
          url: `http://127.0.0.1:8088/order/updateById`,
          method: 'POST',
		  data: userOrder,
          success: (res) => {
            if (res.data.code === 200) {
              uni.showToast({
                title: '已确认收货',
                icon: 'success'
              })
              // 刷新订单列表
              fetchOrders()
            } else {
              uni.showToast({
                title: '操作失败: ' + res.data.message,
                icon: 'none'
              })
            }
          },
          fail: (err) => {
            console.error('确认收货失败:', err)
            uni.showToast({
              title: '网络请求失败',
              icon: 'none'
            })
          },
          complete: () => {
            // 重置按钮状态
            isProcessing[orderId] = false
          }
        })
      } else {
        // 用户取消操作，重置按钮状态
        isProcessing[orderId] = false
      }
    }
  })
}
</script>

<style>
.page {
  padding: 20rpx;
  background-color: #f5fffa; /* 薄荷绿背景 */
}

.header {
  margin-bottom: 30rpx;
  text-align: center;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #20b2aa; /* 薄荷绿标题色 */
}

.search-box {
  margin: 20rpx 0;
  padding: 15rpx;
  background-color: #fff;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.05);
}

.search-input {
  height: 70rpx;
  padding: 0 20rpx;
  background-color: #f0f8ff; /* 浅蓝色输入框 */
  border-radius: 8rpx;
}

/* 订单详情整体容器 */
.order-detail {
  background-color: #fff;
  border-radius: 8rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.05);
}

/* 订单每一行（标签 + 值） */
.order-item-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.order-label {
  font-weight: bold;
  color: #008b8b; /* 深薄荷绿文字，作为标签 */
  flex: 0 0 auto;
  margin-right: 20rpx;
}

.order-value {
  color: #556b2f; /* 柔和绿色文字，作为值 */
  flex: 1;
  text-align: right;
}

/* 操作按钮区域 */
.action-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 25rpx;
}

/* 退款按钮 */
.refund-btn {
  flex: 1;
  margin-right: 15rpx;
  padding: 15rpx;
  background-color: #f5f5f5;
  color: #e64340; /* 红色文字 */
  border: 1rpx solid #e64340;
  border-radius: 8rpx;
  text-align: center;
  font-size: 28rpx;
}

/* 确认收货按钮 */
.confirm-btn {
  flex: 1;
  padding: 15rpx;
  background-color: #20b2aa; /* 薄荷绿背景 */
  color: #fff;
  border-radius: 8rpx;
  text-align: center;
  font-size: 28rpx;
}

/* 按钮禁用状态 */
.refund-btn[disabled], .confirm-btn[disabled] {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 加载状态样式 */
.loading-container {
  padding: 50rpx;
  text-align: center;
  color: #008b8b;
}

/* 空状态样式 */
.empty-container {
  padding: 50rpx;
  text-align: center;
  color: #556b2f;
}
</style>
